package com.bei_en.common.web.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.util.WebUtils;

/**
 * Xss过滤器,可处理multipart请求
 * 
 * @author Guocg
 * 
 */
public class XssFilter extends OncePerRequestFilter {

	private MultipartResolver multipartResolver;

	public XssFilter() {

	}

	@Override
	protected void initFilterBean() throws ServletException {

		XssCommonsMultipartResolver resolver = new XssCommonsMultipartResolver();
		multipartResolver = resolver;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		boolean multipartRequestParsed = false;
		HttpServletRequest req = new XssHttpServletRequestWrapper(request);
		if (multipartResolver.isMultipart(req)) {
			req = multipartResolver.resolveMultipart(req);
			multipartRequestParsed = true;
		}

		try {
			filterChain.doFilter(req, response);
		} finally {
			if (multipartRequestParsed) {
				multipartResolver.cleanupMultipart(WebUtils.getNativeRequest(
						request, MultipartHttpServletRequest.class));
			}
		}
	}

}
